package com.intelligencesoft.pss.realm.auth;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.intelligencesoft.pss.entity.base.UserInfo;
import com.intelligencesoft.pss.service.auth.AuthService;
import com.intelligencesoft.pss.utils.auth.AuthEncryption;



/**
 * 登录
 * 
 * 
 */
@Component
public class UserPassShiroDataRealm extends AuthorizingRealm {

	@Autowired
	private AuthService authService;
	@Autowired
	private AuthEncryption authEncryption;

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		CustomUsernamePasswordToken customUsernamePasswordToken = (CustomUsernamePasswordToken) token;
		String username = customUsernamePasswordToken.getUsername();
		String password = authEncryption.md5Hash(customUsernamePasswordToken.getPassword());
		if (username != null && !"".equals(username)) {
			UserInfo user = authService.findUserinfoByAuth(username, password);
			return new SimpleAuthenticationInfo(user, user.getPassword(),
					getName());
		}
		return null;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		/*// 获取用户响应的permission
		List<String> permissions = new ArrayList<String>();// demo
		// permissions.add("{type:公司,id:aa,role:admin}");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(permissions);
		return info;*/
		return null;
	}
}
